﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;

namespace Savage.DotNetLibrary.DatabaseLibrary
{
    public class SqlServerInstance
    {
        public SqlServerInstance(string connectionString)
        {
            _sqlDataWrapper = new SqlDataWrapper(connectionString);
        }

        private SqlDataWrapper _sqlDataWrapper;

        /// <summary>
        /// Creates a database with the specified name on the SQL server specified in the connection string. 
        /// </summary>
        /// <param name="databaseName">The name to give to the database.</param>
        public void CreateDatabase(string databaseName)
        {
            if (databaseName == null)
                throw new ArgumentNullException("databaseName");

            //Escape and trim the roleName
            databaseName = databaseName.Trim().Replace("]", "]]");

            //Build the sql
            string cmdText = String.Format(CultureInfo.InvariantCulture, "CREATE DATABASE [{0}]", databaseName);

            _sqlDataWrapper.ExecuteNonQuery(cmdText);
        }

        /// <summary>
        /// Deletes the database with the specified name on the SQL server specified in the connection string 
        /// </summary>
        /// <param name="databaseName">The name of the database to delete.</param>
        public void DropDatabase(string databaseName)
        {
            if (databaseName == null)
                throw new ArgumentNullException("databaseName");

            //Escape and trim the roleName
            databaseName = databaseName.Trim().Replace("]", "]]");

            //Build the sql
            string cmdText = String.Format(CultureInfo.InvariantCulture, "DROP DATABASE [{0}]", databaseName);

            _sqlDataWrapper.ExecuteNonQuery(cmdText);
        }

        /// <summary>
        /// Returns a list of the database names that have been created on the server.
        /// </summary>
        /// <returns>A string array of database names.</returns>
        public string[] GetDatabases()
        {
            string cmdText = "SELECT [Name] FROM [sys].[sysdatabases]";

            return _sqlDataWrapper.ExecuteReaderToStringArray(cmdText, System.Data.CommandType.Text, null, "Name");
        }
    }
}
